package com.googlecode.monitoring.webpages.service;

import com.googlecode.monitoring.dao.StatisticDao;
import com.googlecode.monitoring.model.ItemToCheck;
import com.googlecode.monitoring.model.StateName;
import com.googlecode.monitoring.service.MonitoringService;
import com.googlecode.monitoring.webpages.model.WebPageItemToCheck;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Author: Sergiy Doroshenko
 * Date: Aug 31, 2010
 * Time: 5:07:22 PM
 */
@Service(value = "monitoringService")
public class WebPagesMonitoringService implements MonitoringService {
    private Logger log = Logger.getLogger(WebPagesMonitoringService.class);
    private StatisticDao statisticDao;

    @Autowired
    public void setStatisticDao(StatisticDao statisticDao) {
        this.statisticDao = statisticDao;
    }

    @Override
    public boolean checkIsItemOutdated(ItemToCheck item) {
        WebPageItemToCheck itemToCheck = (WebPageItemToCheck) item;
        boolean testfailed = false;
        try {
            URL webPage = new URL(itemToCheck.getWebPage().getUrl());
            HttpURLConnection connection = (HttpURLConnection) webPage.openConnection();
            connection.connect();
            log.debug("Trying to ping " + itemToCheck.getWebPage().getUrl());
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                connection.disconnect();
                throw new RuntimeException("The page '" + itemToCheck.getWebPage().getUrl() + "' does not respond");
            }
            connection.disconnect();
            itemToCheck.switchState(StateName.CHECKED);
            itemToCheck.setLastCheckTime(new DateTime());
            log.debug("The page responds");
            statisticDao.incrementTotalStateChecks(itemToCheck.getId());
        } catch (Throwable e) {
            testfailed = true;
            log.debug("The page does not respond");
            statisticDao.incrementTotalStateDownChecks(itemToCheck.getId());
        }
        return testfailed;
    }
}
